const api = require('../../api/api')
const app = getApp()
const util = require('../../utils/js/util')
Page({
  data: {
    userInfo: app.globalData.userInfo,
    id: '', // 服务id
    backtop: util.getMenuButton().top, // 返回图标的top位置
    info: {}, // 服务信息
    popshow: false,
    safebottom: util.getSafeToBottom(),
    patient: [], // 就诊人列表
    listStatus: 'loading',
    page: 1, // 页码
    isUpOrder: false,
    agreeTap: true
  },
  async onLoad(options) {
    options?.id && this.setData({ id: options.id })
    this.getinfo()
    await this.getPatient()
    wx.createIntersectionObserver().relativeTo('#list-container', { bottom: 10 }).observe('#bottomline', (res) => {
      if (res.intersectionRatio > 0 && this.data.listStatus == 'loading' && this.data.patient.length >= 10) {
        this.setData({ page: this.data.page + 1 })
        this.getPatient()
      }
    })
  },
  // 获取就诊人列表
  async getPatient() {
    const res = await api.getClientList({ p: this.data.page })
    const newdata = res.data.map(v => ({
      ...v,
      age: new Date().getFullYear() - new Date(v.birthday).getFullYear(),
    }))
    this.setData({
      patient: this.data.page == 1 ? newdata : this.data.patient.concat(newdata),
      listStatus: res.current_page == res.last_page ? 'tobottom' : res.current_page < res.last_page ? 'loading' : res.current_page > res.last_page ? 'nodata' : ''
    })
  },
  // 获取服务信息
  async getinfo() {
    const res = await api.getService({ id: this.data.id })
    this.setData({ info: res })
  },
  // 跳过
  async jump() {
    if(this.data.isUpOrder == false) {
      this.setData({ isUpOrder: true })
      const res = await api.addOrder({ service_id: this.data.id })
      util.toast('下单成功')
      setTimeout(() => wx.navigateTo({ url: "../purchased/index?id=" + res.id + '&type=service' }), 500);
    }
  },
  // 选择就诊人去购买
  async gotobuy({ currentTarget: { dataset: { item } } }) {
    if(this.data.agreeTap) {
      this.setData({ agreeTap: false })
      const res = await api.addOrder({ service_id: this.data.id })
      await api.updateOrder({ id: res.id, client_id: item.id })
      util.toast('下单成功')
      setTimeout(() => {
        wx.navigateTo({ url: "../purchased/index?id=" + res.id + '&type=service' })
        this.setData({ agreeTap: true })
      }, 500);
    }
  },
  // 点击购买服务按钮
  buy() {
    this.setData({ popshow: true })
  },
  // 返回
  back() {
    wx.navigateBack()
  },
  // 管理就诊人
  gotoPatient() {
    wx.navigateTo({ url: '../patient/index' })
  },
})
